#pragma once

#include <iostream>
#include "Log.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include <string>
#include <vector>
#include <queue>
#include <unistd.h>

namespace ThreadPoolModule
{
    using namespace ThreadModlue;
    using namespace LogModule;
    using namespace CondMoule;
    using namespace MutexMouble;

    static const int gnum = 15;

    template<class T>
    class ThreadPool
    {
    private:
        void WakeupAll()
        {
            if(_sleepnum == 0) return;
            _cond.Broadcast();
            LOG(LogLevel::INFO) << "唤醒所有休眠的线程";
        }
        void WakeupOne()
        {
            _cond.Siganl();
            LOG(LogLevel::INFO) << "唤醒一个休眠的线程";
        }

        ThreadPool(int num = gnum)
            :_num(num), _isrunning(false), _sleepnum(0)
        {
            for(int i = 0; i < num; i++)
            {
                _threads.emplace_back([this](){ HandlerTask(); }); 
            }
            LOG(LogLevel::INFO) << "create thread success";
        }
        
        void Start()
        {
            if(_isrunning) return;
            _isrunning = true;
            for(auto &thread : _threads)
            {
                thread.Start();
                LOG(LogLevel::INFO) << thread.Name() << " start success";
            }
        }

        ThreadPool(const ThreadPool<T>&) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T>&) = delete;
    public:
        static ThreadPool<T> *GetInstance()
        {   if(inc == nullptr)
            {
                LockGuard lockguard(_lock);
                if(inc == nullptr)
                {   
                    LOG(LogLevel::DEBUG) << "首次获取单例,创建对象";
                    inc = new ThreadPool<T>();
                    inc->Start();
                }
            }   
            return inc;
        }       

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while(true)
            {
                T t;
                {
                    LockGuard lockguard(_mutex);
                    while(_taskq.empty() && _isrunning)
                    {
                        _sleepnum++;
                        _cond.Wait(_mutex);
                        _sleepnum--;
                    }

                    if(!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << "退出且任务队列为空";
                        break;
                    }

                    //一定有任务
                    t = _taskq.front();
                    _taskq.pop();
                }
                t(); // 处理任务不在临界区:可以实现并行处理任务
            }
        }

        void Stop()
        {
            if(!_isrunning) return;
            _isrunning = false;

            //唤醒所有线程
            WakeupAll();
        }

        void Join()
        {
            for(auto &thread : _threads)
            {
                thread.Join();
            }
        }

        bool Equeue(const T &in)
        {
            if(!_isrunning)
            {
                LOG(LogLevel::WARNING) << "threadPool已经停止运行不能处理任务";
                return false;
            }
            LockGuard lockguard(_mutex);
            _taskq.push(in);
            if(_threads.size() == _sleepnum)
                WakeupOne();
            return true;
        }

        ~ThreadPool(){}
    private:
        std::vector<Thread> _threads;
        int _num;
        std::queue<T> _taskq;
        Cond _cond;
        Mutex _mutex;
        bool _isrunning;
        int _sleepnum;

        static ThreadPool<T> *inc;
        static Mutex _lock;
    };

    template<class T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr;
    template<class T>
    Mutex ThreadPool<T>::_lock;
}